#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>

#define MAX_IP_LENGTH 11
#define PORTLENGHT 5
#define CONFIGFILEPATH "./configC"
#define STRINGLENGHT 255

typedef struct {
    char ip[MAX_IP_LENGTH];
    char port[PORTLENGHT];
}fileConfig;

/** check for configuration end of file */
int endOfFile(int fd, char buffer[MAX_IP_LENGTH]) {
	return read(fd, buffer, 1) > 0;
}

fileConfig readConfig()
{
	int fd,maxAllow = 0;
	fileConfig archConf;
	char aux[255] ="";
	char *buffer = (char *)malloc(sizeof(255));
	
	fd = open(CONFIGFILEPATH,O_RDONLY,0777);
	if (fd == 0)
	{
		perror("error al intentar abrir el archivo configC\n");
		exit(-1);
	}	
	while (endOfFile(fd, buffer)) {
		if (strcmp(buffer,"\n") != 0){
			strcat(aux,buffer);
		}
		else
		{
			strcat(aux,"\0");
			switch (maxAllow) {
			case 0: 
				strcpy(archConf.ip,aux);
				maxAllow = 1;
				break;
			default:
				strcpy(archConf.port,aux);
				break;
			}
			strcpy(aux,"");
		}
	}

	return archConf;
}

int initializeSocket(fileConfig fc)
{
	int sock;
	struct sockaddr_in socketStruct;
	sock = socket( AF_INET, SOCK_STREAM, 0);
  	if (sock != -1) {
  		socketStruct.sin_family = AF_INET;
		socketStruct.sin_port = htons(atoi(fc.port));
		socketStruct.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
			perror("error al al asignar al crear el socket\n");
			exit(-1);
	}
	return sock;
}

int acceptSocket(int sSocket)
{
	int sock;
	struct sockaddr_in socketStruct;
	sock = connect(sSocket,(struct sockaddr *)&socketStruct ,sizeof(socketStruct));

	if (sock < 0)
	{
		perror("error al al aceptar el socket\n");
		exit(-1);
	}
	return sSocket;
}

void getCommand(int sock)
{
	char command[STRINGLENGHT], response[STRINGLENGHT];
	
	do
	{
		gets(command);
		
		write(sock,command,sizeof(command));
		 
		int n = read(sock,response,STRINGLENGHT);    
		response[n]='\0';
		printf("%s\n",response);
	}
	while(strcmp(response,"1") != 0);
}

int main()
{
	fileConfig configuration = readConfig();
	int sock = acceptSocket(initializeSocket(configuration));
	getCommand(sock);
	
	close(sock);
	return 0;
}
